package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path"
	"strconv"
	"time"
	. "xm_shop/database"
	. "xm_shop/models"
)

type SettingController struct{}

// 检索设置信息
func (s SettingController) Index(context *gin.Context) {
	var setting Setting
	DB.Take(&setting)
	context.JSON(http.StatusOK, gin.H{
		"data": setting,
	})
}

// 编辑设置信息
func (s SettingController) Edit(context *gin.Context) {
	var setting Setting
	DB.Where("id = ", 1).Take(&setting)
	if err1 := context.ShouldBind(&setting); err1 != nil {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	// 处理文件上传
	file1, err5 := context.FormFile("site_logo")
	file2, err7 := context.FormFile("no_picture")
	if err5 != nil || err7 != nil {
		context.String(http.StatusBadRequest, "文件上传失败")
		return
	}
	// 获取文件后缀
	extName1 := path.Ext(file1.Filename)
	extName2 := path.Ext(file2.Filename)
	// 创建合法后缀map映射
	allowExtMap := map[string]bool{
		".jpg":  true,
		".jpeg": true,
		".png":  true,
		".gif":  true,
	}
	// 判断文件的合法性
	if _, ok := allowExtMap[extName1]; !ok {
		context.String(http.StatusBadRequest, "文件不合法")
		return
	}
	if _, ok := allowExtMap[extName2]; !ok {
		context.String(http.StatusBadRequest, "文件不合法")
		return
	}
	// 获取当前日期
	day := time.Now().Format("20060102")
	// 指定文件存储目录
	dir := "./static/upload/" + day
	// 迭代创建目录
	os.MkdirAll(dir, 0666)
	// 获取当前时间戳的字符串形式
	fileName1 := strconv.FormatInt(time.Now().Unix(), 10) + extName1 // 不要忘记拼接后缀
	time.Sleep(1 * time.Second)                                      // 防止文件重复
	fileName2 := strconv.FormatInt(time.Now().Unix(), 10) + extName2
	// 拼接文件路径
	dst1 := path.Join(dir, fileName1)
	dst2 := path.Join(dir, fileName2)
	err6 := context.SaveUploadedFile(file1, dst1)
	err8 := context.SaveUploadedFile(file2, dst2)
	if err6 != nil || err8 != nil {
		context.String(http.StatusBadRequest, "文件保存失败")
		return
	}
	setting.SiteLogo = dst1
	setting.NoPicture = dst2
	if err2 := DB.Save(&setting).Error; err2 != nil {
		context.String(http.StatusBadRequest, "修改失败")
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"success": true,
	})
}
